package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.LoginFailedException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.OrderService;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderSubmitImpl implements OrderService {
  @Autowired
  private OrderMapper orderMapper;
  @Autowired
  private OrderDetailMapper orderDetailMapper;
  @Autowired
  private AddressBookMapper addressBookMapper;
  @Autowired
  private ShoppingCartMapper shoppingCartMapper;
  @Autowired
  private WebSocketServer webSocketServer;

  /**
   * 用户下单
   * @param ordersSubmitDTO
   * @return
   */
  @Override
  @Transactional
  public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
    // 1. 入库前处理各种业务异常（地址为空、购物车数据为空）
    Long addressBookId = ordersSubmitDTO.getAddressBookId();
    AddressBook address = addressBookMapper.getById(addressBookId);
    if(address == null) {
      throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
    }

    Long userId = BaseContext.getCurrentId();
    List<ShoppingCart> shoppingCarts = shoppingCartMapper.getListByUserId(userId);
    if(shoppingCarts == null || shoppingCarts.size() == 0){
      throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
    }

    // 2. 向订单表插入一条数据
    Orders orders = new Orders();
    BeanUtils.copyProperties(ordersSubmitDTO,orders);
    orders.setOrderTime(LocalDateTime.now());
    orders.setPayStatus(Orders.UN_PAID);
    orders.setStatus(Orders.PENDING_PAYMENT);
    orders.setNumber(String.valueOf(System.currentTimeMillis()));
    orders.setPhone(address.getPhone());
    orders.setConsignee(address.getConsignee());
    orders.setUserId(userId);
    orderMapper.insert(orders);// mapper里面需要把主键id封装到orders中
    // 3. 向订单明细表插入n条数据
    List<OrderDetail> list = new ArrayList<>();
    for (ShoppingCart shoppingCart : shoppingCarts) {
      OrderDetail orderDetail = new OrderDetail();
      BeanUtils.copyProperties(shoppingCart,orderDetail);
      orderDetail.setOrderId(orders.getId());
      list.add(orderDetail);
    }
    orderDetailMapper.insertBatch(list); // 批量插入订单明细
    // 4. 下单完成后，清空用户购物车数据
    shoppingCartMapper.clear(userId);
    // 模拟支付成功后，推送提醒到后台


    //webSocketServer.sendToAllClient("您有一条新的订单提醒");
    /*Map map  = new HashMap();
    map.put("orderId",orders.getId());
    map.put("type",1);
    map.put("content","您有一条新的订单,订单号：" + orders.getId());
    String wsjson = JSON.toJSONString(map);
    webSocketServer.sendToAllClient(wsjson);*/

    // 5. 返回OrdersSubmitVo
    return OrderSubmitVO.builder()
      .id(orders.getId())
      .orderAmount(orders.getAmount())
      .orderNumber(orders.getNumber())
      .orderTime(orders.getOrderTime())
      .build();
  }
}
